﻿using System.Data;
using System.Diagnostics;
using System.Text;

namespace Protocal.App.Server.Middles
{
    public class ExceptionHandle
    {
        private readonly RequestDelegate _next;

        public ExceptionHandle(IConfiguration configuration, RequestDelegate next)
        {
            _configuration = configuration;
            _next = next;
            DB = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = _configuration.GetValue<string>("ConnectionStrings:url"),
                DbType = DbType.MySql,
                IsAutoCloseConnection = true
            });
        }

        public async Task Invoke(HttpContext context)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();

            ApiAccessLog model = new ApiAccessLog()
            {
                Url = context.Request.Path.Value,
                Method = context.Request.Method,
                QueryString = context.Request.QueryString.Value,
                OriginIP = context.Connection.RemoteIpAddress.ToString(),
                AccessTime = DateTime.Now,
            };
            try
            {
                await _next.Invoke(context);
            }
            catch (Exception ex)
            {
                model.Msg = ex.Message;
                byte[] errMsgBytes = Encoding.UTF8.GetBytes(ex.Message);
                Stream stream = context.Response.Body;
                context.Response.StatusCode = 500;
                context.Response.ContentLength = errMsgBytes.Length;
                await stream.WriteAsync(errMsgBytes);
                context.Response.Body = stream;
            }
            finally
            {
                stopwatch.Stop();
                // 毫秒
                long timeCount = stopwatch.ElapsedMilliseconds;
                model.StatusCode = context.Response.StatusCode;
                model.ExecuteTime = timeCount;
                await DB.Insertable<ApiAccessLog>(model).ExecuteCommandAsync();
            }
        }
    }
}
